<?php namespace Admin\Controller;
use Hdphp\Controller\Controller;
// 商品控制器
class GoodsController extends CommonController{
	private $model;
	private $gid;
//	商品属性
	private $gAttrModel;
//	商品内容
	private $gDetailModel;
//	构造方法
	public function __init(){
		parent::__init();
		$this->model = new \Admin\Model\Goods;
		$this->gAttrModel = new \Admin\Model\GoodsAttr;
		$this->gDetailModel = new \Admin\Model\GoodsDetail;
	}
//	显示列表页
	public function index(){
//		统计数据总数
		$total = $this->model->count();
		$page = Page::row(6)->make($total);
//		查询数据库
		$goodsData = $this->model->limit(Page::limit())->get();
//		sp($goodsData);
//		分配商品表里的数据
		View::with('goodsData',$goodsData);
//		分配页数
		View::with('page',$page);
		View::make();
	}
//	修改商品
	public function edit(){
//		2、提交修改
		if(IS_POST){
//			sp($_POST);exit;
			$gid = Q('post.gid',0,'intval');
//			1、修改商品表
			if(!$this->model->edit($gid)) View::error($this->model->getError());
//			2、修改商品属性表
			if(!$this->gAttrModel->edit($gid)) View::error($this->gAttrModel->getError());
//			3、修改商品详细表
			if(!$this->gDetailModel->edit($gid)) View::error($this->gDetailModel->getError());
			View::success("修改成功",U('index'));
		}
//		1、获取旧数据
//		接受Gid
		$gid = Q('get.gid',0,'intval');
//		(1)查询分类数据
		$cateData = Db::table('category')->get();
//		转成树状结构
		$cateData = Data::tree($cateData,'cname');
//		分配 分类数据
		View::with('cateData',$cateData);
//		sp($cateData);
//		(2)查询品牌数据
		$brandData = Db::table('brand')->get();
//		分配品牌数据
		View::with('brandData',$brandData);
//		（3）查询商品表数据
		$GoodsData = $this->model->where("gid={$gid}")->find();
//		sp($GoodsData);
		View::with('GoodsData',$GoodsData);
//		（4）查询商品属性表(只获取 属性)
		$gsAttrData = Db::table('goods_attr')->join("type_attr","type_attr_taid","=","taid")->where("goods_gid={$gid} AND taclass=0")->get();
//		sp($gsAttrData);
//		$gsAttrTotal = Db::table('goods_attr')->join("type_attr","type_attr_taid","=","taid")->where("goods_gid={$gid} AND taclass=0")->count();
//		sp($gsAttrTotal);
//		循环添加
		foreach($gsAttrData as $k => $tavalue){
//			$tavalueArr['']
			$gsAttrData[$k]['attr'] = explode(',',$tavalue['tavalue']);
		}
//		sp($gsAttrData);
//		分配属性（不可选）
		View::with('gsAttrData',$gsAttrData);
//		(5)查询商品属性表，只获取规格
		$ggAttrData = Db::table('goods_attr')->join("type_attr","type_attr_taid","=","taid")->where("goods_gid={$gid} AND taclass=1")->get();
//		空数组
//		sp($ggAttrData);
		foreach($ggAttrData as $kk => $vv){
			$ggAttrData[$kk]['spec'] = explode(',',$vv['tavalue']);
		}
//		sp($ggAttrData);
		View::with('ggAttrData',$ggAttrData);
//		（6）查询商品详细
		$gDetailData = Db::table('goods_detail')->where("goods_gid={$gid}")->get();
//		分配变量
		View::with('gDetailData',$gDetailData);
//		sp($gDetailData);
//		分配 图片数组
		$gDetailImg = explode(',',$gDetailData[0]['img']);
//		sp($gDetailImg);
		View::with('gDetailImg',$gDetailImg);
		View::make();
	}
//	删除商品
	public function del(){
//		获得要删的Gid
		$gid = Q('get.gid',0,'intval');
//		查询图片路径
		$imgPath = $this->gDetailModel->where("goods_gid={$gid}")->find();
//		将字符串转变成数组
		$NewimgPath = explode(',',$imgPath['img']);
		if($this->model->del($gid)){
			foreach($NewimgPath as $k=>$v){
				unlink($v);
			}
			View::success('删除成功',U('index'));
		}
	}
//	添加商品
	public function add(){
		if(IS_POST){
//			sp($_POST);exit;
//			重组数组
				$goodsarr = array();
				$addtime = time();
				$goodsarr = array(
					'gname' =>$_POST['gname'],
					'nick_name' =>$_POST['nick_name'],
					'des' =>$_POST['des'],
					'unit' => $_POST['unit'],
					'artnum'=>$_POST['artnum'],
					'market_price' => $_POST['market_price'],
					'shop_price' =>$_POST['shop_price'],
					'inventory' =>$_POST['inventory'],
					'click' =>$_POST['click'],
					'brand_bid' =>$_POST['brand_bid'],
					'category_cid' =>$_POST['category_cid'],
					'type_tid' =>$_POST['type_tid'],
					'lists_pic'=>$_POST['lists_pic'],
					'time' =>$addtime,
					'user_admin_uid' => $_SESSION['uid']
				);
//				sp($goodsarr);exit;
			if($gid = $this->model->store($goodsarr)){
				$this->gid = $gid;
//				sp($pid);
//				添加商品属性表goods_attr
				foreach(Q('post.attr',array()) as $taid => $tavalue){
					if($tavalue){
						$attrData = array(
							'type_attr_taid'=>$taid,
							'gavalue' => $tavalue,
							'goods_gid'=>$this->gid
						);
//						sp($attrData);
//						如果添加成功
						if(!$this->gAttrModel->store($attrData)) View::error($this->gAttrModel->getError());
					}
				}
				$ggData = array();
//				商品规格插入goods_attr  $key是  $taid
				foreach(Q('post.spec') as $key => $value){
					if($value){
//						sp($key);
						$ggData['type_attr_taid'] = $key;
						$ggData['goods_gid'] = $this->gid;
//						sp($value);
//						sp($value['price']);
						foreach($value['value'] as $k => $v){
							$ggData['gavalue'] = $v;
							$ggData['add_price'] = $value['price'][$k];
							$this->gAttrModel->store($ggData);
						}
					}
				}
//				向商品详细表添加数据
//				空数组
				$img_str = implode(',', Q('post.img',array()));
				$detailArr = array(
					'goods_gid' =>$this->gid,
					'detail' => Q('post.detail'),
					'img' =>$img_str,
					'serve' =>Q('post.serve')
				);
					if(!$this->gDetailModel->store($detailArr)) View::error($this->gDetailModel->getError());			
				View::success('成功添加',U('index'));
			}else{
				View::error($this->model->getError());
			}
		}
//		1、获取商品分类
//		不实例化分类模型了
		$cateData = Db::table('category')->get();
		$brandData = Db::table('brand')->get();
//		sp($brandData);
//		转成树状结构
		$cateData = Data::tree($cateData,'cname');
//		sp($cateData);
//		分配分类数据
		View::with('cateData',$cateData);
//		分配品牌数据
		View::with('brandData',$brandData);
		View::make();
	}
//	ajax接受
	public function ajaxGetAttr(){
		if(IS_AJAX){
//			通过类型id查询类型属性
			$tid = Q('post.tid',0,'intval');
			$typeData = Db::table('type_attr')->where("type_tid={$tid}")->get();
//			sp($typeData);
//			(array)强制弄成数组
			foreach((array)$typeData as $k => $v){
//				弄成三维数组
				$typeData[$k]['tavalue'] = explode(',', $v['tavalue']);
			}
			echo json_encode($typeData);
			exit;
//			sp($typeData);
		}
	}
	//uploadify异步上传
	public function upload()
	{
	    $file = Upload::path('Upload/Content/' . date('y/m'))->make();
	    if (empty($file)) {
	        $this->ajax(Upload::getError());
	    } else {
	        /** $file内部就是以下这个数组
	            $file = array(
	                0 => array(
	                'path' => 'Upload/Content/15/8/123981239172.jpg'    ,
	                'url' => 'http://localhost/cms_edu/Upload/Content/15/8/123981239172.jpg',
	                'image' => 1
	            ),
	        );**/
	        //上传成功，把上传好的信息返给js
	        $data = $file[0]["path"];
	        echo json_encode($data);exit;
	    }
	}
	//uploadify异步上传多种
	public function upload_more()
	{
	    $file = Upload::path('Upload/Content/' . date('y/m'))->make();
//		缩略图目录
		$biguploadDir = 'Upload/magnifier/'.'/big/';
		$miduploadDir = 'Upload/magnifier/'.'/mid/';
		$smalluploadDir = 'Upload/magnifier/'.'/small/';
	    if (empty($file)) {
	        $this->ajax(Upload::getError());
	    } else {
	        /** $file内部就是以下这个数组
	            $file = array(
	                0 => array(
	                'path' => 'Upload/Content/15/8/123981239172.jpg'    ,
	                'url' => 'http://localhost/cms_edu/Upload/Content/15/8/123981239172.jpg',
	                'image' => 1
	            ),
	        );**/
////			生成缩略图（1、上传图片的路径，2、缩略图的名字，3、width，4、height，5、缩略方式）
	        $BigPath = Image::thumb($file[0]['path'],$biguploadDir.$file[0]['basename'],800,800,1);
			$MiddlePath = Image::thumb($file[0]['path'],$miduploadDir.$file[0]['basename'],480,480,1);
			$SmallPath = Image::thumb($file[0]['path'],$smalluploadDir.$file[0]['basename'],60,60,1);
	        //上传成功，把上传好的信息返给js
	        $data = $file[0];
	        echo json_encode($data);exit;
	    }
	}
}




 ?>